//
//  ShopViewController.swift
//  Eternity
//
//  Created by ZhengWei on 2016/11/27.
//  Copyright © 2016年 ZhengWei. All rights reserved.
//

import UIKit
import SwiftyJSON

class ShopViewController: BaseViewController {

    var shopModel: ShopModel?
    var categoryIds: [NSNumber]?
    var listArrOne: [ListOfGoodsModel]?
    var listArrTwo: [ListOfGoodsModel]?
    
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        initBaseLayout()
        initNavTitleView(controller: self)
        initNavItem(controller: self, imageName: "nav_search_n", highlitedImageName: "nav_search_h", selectedImageName: "", isLeft: false)
        
        initModel()
        dataRequst()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // MARK: - private method
    func initBaseLayout() {
        self.view.addSubview(shopCollection)
    }

    func initModel() {
        shopModel = ShopModel()
        shopModel?.bestSellerList = [ListOfGoodsModel]()
        shopModel?.newList = [ListOfGoodsModel]()
        shopModel?.recommendList = [ListOfGoodsModel]()
        shopModel?.productCategorylist = [CategoryListModel]()
        shopModel?.focusBannerList = [FocusBannerModel]()
        shopModel?.advDetailList = [ListOfGoodsModel]()
        categoryIds = [NSNumber]()
        listArrOne = [ListOfGoodsModel]()
        listArrTwo = [ListOfGoodsModel]()
    }
    
    func dataRequst() {
        NetManager.sharedInstance.postRequest(urlString: "/v1/index", params: Dictionary(), success: { (response) in
            let dataDic = response
            // 热卖商品数据
            let bestSellerList = dataDic["bestSellerList"] as! [[String: AnyObject]]
            for item in bestSellerList {
                let bestSellerModel = ListOfGoodsModel()
                bestSellerModel.setValuesForKeys(item)
                let dic = item["brand"] as? [String: AnyObject]
                bestSellerModel.brandName = dic?["brandName"] as! String?
                self.shopModel?.bestSellerList?.append(bestSellerModel)
            }
            
            // 新品首发
            let newList = dataDic["newList"] as! [[String: AnyObject]]
            for item in newList {
                let newListModel = ListOfGoodsModel()
                newListModel.setValuesForKeys(item)
                let dic = item["brand"] as? [String: AnyObject]
                newListModel.brandName = dic?["brandName"] as! String?
                self.shopModel?.newList?.append(newListModel)
            }
            
            // 猜你喜欢
            let recommendList = dataDic["recommendList"] as! [[String: AnyObject]]
            for item in recommendList {
                let recommendModel = ListOfGoodsModel()
                recommendModel.setValuesForKeys(item)
                let dic = item["brand"] as? [String: AnyObject]
                recommendModel.brandName = dic?["brandName"] as! String?
                self.shopModel?.recommendList?.append(recommendModel)
            }
            
            // 四大分类以及广告图
            let productCategoryList = dataDic["productCategorylist"] as! [[String: AnyObject]]
            for item in productCategoryList {
                let categoryListModel = CategoryListModel()
                categoryListModel.setValuesForKeys(item)
                self.shopModel?.productCategorylist?.append(categoryListModel)
                self.categoryIds?.append(categoryListModel.categoryId!)
            }
            
            // 轮播图
            let focusBannerList = dataDic["focusBannerList"] as! [[String: AnyObject]]
            for item in focusBannerList {
                let focusBannerModel = FocusBannerModel()
                focusBannerModel.setValuesForKeys(item)
                self.shopModel?.focusBannerList?.append(focusBannerModel)
            }
            
            if (self.categoryIds?.count)! >= 5 {
                for i in 4 ..< self.categoryIds!.count {
                    var dic = [String: Any]()
                    dic["categoryId"] = self.categoryIds?[i]
                    NetManager.sharedInstance.postRequest(urlString: "/v1/product/list", params: dic, success: { (response) in
                        print(response)
                        let listArr = response["list"] as! [[String: AnyObject]]
                        
                        if i == 4 {
                            for item in listArr {
                                let advDetailModel = ListOfGoodsModel()
                                advDetailModel.setValuesForKeys(item)
                                let brand = item["brand"] as? [String: AnyObject]
                                advDetailModel.brandName = brand?["brandName"] as! String?
                                self.listArrOne?.append(advDetailModel)
                            }
                        } else if  i == 5 {
                            for item in listArr {
                                let advDetailModel = ListOfGoodsModel()
                                advDetailModel.setValuesForKeys(item)
                                let brand = item["brand"] as? [String: AnyObject]
                                advDetailModel.brandName = brand?["brandName"] as! String?
                                self.listArrTwo?.append(advDetailModel)
                            }
                        }
                        
                        self.shopCollection.reloadData()
                        
                    }, failture: { (error) in
                        print(error)
                    })
                }
            }
            self.shopCollection.reloadData()
            
        }) { (error) in
            print(error)
        }
        
    }
    
    // MARK: - setters and getters
    var _layout: UICollectionViewFlowLayout!
    var layout: UICollectionViewFlowLayout {
        if _layout == nil {
            _layout = UICollectionViewFlowLayout()
        }
        return _layout
    }
    
    var _shopCollection: UICollectionView!
    var shopCollection: UICollectionView {
        if _shopCollection == nil {
            _shopCollection = UICollectionView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-49), collectionViewLayout: layout)
            _shopCollection.backgroundColor = UIColor(hexString: "#E5E5E5")
//            _shopCollection.backgroundColor = UIColor.white
            _shopCollection.dataSource = self
            _shopCollection.delegate = self
            // 第一组头
            _shopCollection.register(BannerHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "BannerHeader")
            // 第一组cell
            _shopCollection.register(AllTypesCell.self, forCellWithReuseIdentifier: "AllTypesCell")
            // 第二四六组头
            _shopCollection.register(FondHotAndFondHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "FondHotAndFondHeader")
            // 第三五组头
            _shopCollection.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "UICollectionReusableView")
            // 第二三五六组cell
            _shopCollection.register(NewAndFontCell.self, forCellWithReuseIdentifier: "NewAndFontCell")
            // 第四组cell
            _shopCollection.register(NewHotAndFondCell.self, forCellWithReuseIdentifier: "NewHotAndFondCell")
            // 第二四组脚
            _shopCollection.register(NewAndHotFooter.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "NewAndHotFooter")
        }
        return _shopCollection
    }
    
    
}

extension ShopViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    // 返回组数
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 6
    }
    // 返回每组个数
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return 4
        } else if section == 3 {
            if (shopModel?.bestSellerList?.count)! > 0 {
                return (shopModel?.bestSellerList?.count)!
            }
        } else if section == 1 || section == 2 || section == 4 || section == 5 {
            return 1
        }
        return 0
    }
    // 返回cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        
        switch indexPath.section {
        case 0:
            let string = "AllTypesCell"
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: string, for: indexPath) as! AllTypesCell
            
            if (self.shopModel?.productCategorylist?.count)! > 0 {
                cell.configUI(imageUrl: (self.shopModel?.productCategorylist?[indexPath.item].imageURL)!, categoryName: (self.shopModel?.productCategorylist?[indexPath.item].categoryName)!)
            }
            
            return cell
        case 1:
            let string = "NewAndFontCell"
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: string, for: indexPath) as! NewAndFontCell
            if (self.shopModel?.newList?.count)! > 0 {
                cell.configUI(nineList: .NEWLIST, list: (self.shopModel?.newList)!)
            }
            
            return cell
        case 2:
            let string = "NewAndFontCell"
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: string, for: indexPath) as! NewAndFontCell
            if (listArrOne?.count)! > 0 {
                cell.configUI(nineList: .ADVONE, list: listArrOne!)
            }
            return cell
            
        case 3:
            let string = "NewHotAndFondCell"
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: string, for: indexPath) as! NewHotAndFondCell
            
            if (shopModel?.bestSellerList?.count)! > 0 {
                cell.configUI(bestListModel: (shopModel?.bestSellerList?[indexPath.item])!)
            }
            return cell
        case 4:
            let string = "NewAndFontCell"
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: string, for: indexPath) as! NewAndFontCell
            if (listArrTwo?.count)! > 0 {
                cell.configUI(nineList: .ADVTWO, list: listArrTwo!)
            }
            return cell
        case 5:
            let string = "NewAndFontCell"
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: string, for: indexPath) as! NewAndFontCell
            cell.configUI(nineList: .FONDLIST, list: (self.shopModel?.recommendList)!)
            return cell
        default:
            break
        }
        
        return UICollectionViewCell()
    }
    // 返回item大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 0 {
            return CGSize(width: SCREEN_WIDTH/4, height: 84)
        } else if indexPath.section == 3 {
            return CGSize(width: SCREEN_WIDTH/2, height: 244)
        } else if indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 4 || indexPath.section == 5 {
            return CGSize(width: SCREEN_WIDTH, height: 195)
        }
        return CGSize(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 14, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 0 {
            return CGSize(width: SCREEN_WIDTH, height: 170)
        } else if section == 1 || section == 3 || section == 5 {
            return CGSize(width: SCREEN_WIDTH, height: 46)
        }
        return CGSize(width: 0, height: 10)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        if self.shopModel?.productCategorylist?.count == 6 {
            if section == 1 || section == 3 {
                return CGSize(width: SCREEN_WIDTH, height: 170)
            }
        } else if self.shopModel?.productCategorylist?.count == 5 {
            if section == 1 {
                return CGSize(width: SCREEN_WIDTH, height: 170)
            }
        }
        
        return CGSize(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        if kind == UICollectionElementKindSectionHeader {
            
            if indexPath.section == 1 || indexPath.section == 3 || indexPath.section == 5 {
                let string = "FondHotAndFondHeader"
                let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: string, for: indexPath) as! FondHotAndFondHeader
                switch indexPath.section {
                case 1:
                    header.title = "新品首发"
                case 3:
                    header.title = "热卖商品"
                case 5:
                    header.title = "猜你喜欢"
                default:
                    break
                }
                return header
            } else if indexPath.section == 0 {
                let string = "BannerHeader"
                let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: string, for: indexPath) as! BannerHeader
                
                if (self.shopModel?.focusBannerList?.count)! > 0 {
                    var imageUrlArr = [String]()
                    var linkArr = [String]()
                    var titleArr = [String]()
                    for i in 0 ..< shopModel!.focusBannerList!.count {
                        imageUrlArr.append((shopModel?.focusBannerList?[i].picUrl)!)
                        linkArr.append((shopModel?.focusBannerList?[i].link)!)
                        titleArr.append((shopModel?.focusBannerList?[i].title)!)
                    }
                    header.linkArr = linkArr
                    header.titleArr = titleArr
                    header.configUI(imageUrlArr: imageUrlArr)
                }
               
                return header
            } else if indexPath.section == 2 || indexPath.section == 4 {
                let string = "UICollectionReusableView"
                let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: string, for: indexPath)
                header.backgroundColor = UIColor.white
                return header
            }
        } else if kind == UICollectionElementKindSectionFooter {
            let string = "NewAndHotFooter"
            let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: string, for: indexPath) as! NewAndHotFooter
            
            if self.shopModel?.productCategorylist?.count == 6 {
                if indexPath.section == 1 {
                    footer.imageName = self.shopModel?.productCategorylist?[4].cover
                } else if indexPath.section == 3 {
                    footer.imageName = self.shopModel?.productCategorylist?[5].cover
                }
            } else if self.shopModel?.productCategorylist?.count == 5 {
                if indexPath.section == 1 {
                    footer.imageName = self.shopModel?.productCategorylist?[4].cover
                }
            }
            return footer
        }
        
        return UICollectionReusableView()
    }
    
    
}


